package cn.asura.otherChat.util;

import java.io.*;
import java.net.Socket;

public class ClientTool {
    public static void createLocalStrange(String username) {
        File file = new File("./storage/client/" + username);
        if (file.exists()) {
            System.out.println("本地存储的目录已经存在：" + file.getPath());
        } else {
            System.out.println(file.mkdirs() ? "本地存储的目录创建成功：" + file.getPath() : "本地存储的目录创建失败：" + file.getPath());
        }
    }

    public static void sendFile(File file, Socket socket) {
        // 如果文件存在，则使用文件流发送文件到服务器
        BufferedInputStream bis = null;
        BufferedOutputStream bos;
        try {
            bis = new BufferedInputStream(new FileInputStream(file));
            bos = new BufferedOutputStream(socket.getOutputStream());

            // 开始发送
            byte[] bytes = new byte[1024];
            int res;
            while ((res = bis.read(bytes)) != -1) {
                bos.write(bytes, 0, res);
                bos.flush();
            }

            System.out.println("文件发送成功");

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    public static void receiveFileFromServer(Socket socket, File file) {
        BufferedInputStream bis;
        BufferedOutputStream bos = null;
        try {
            bis = new BufferedInputStream(socket.getInputStream());
            bos = new BufferedOutputStream(new FileOutputStream(file));

            // 获取文件
            byte[] bytes = new byte[1024];
            int res;
            while ((res = bis.read(bytes)) > 0) {
                bos.write(bytes, 0, res);
                bos.flush();
                if (res < 1024) {
                    break;
                }
            }
            System.out.println("文件 " + file.getName() + " 已经保存到本地");

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != bos) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}
